<template>
  <div class="home-container">
    <!--    爬取状态栏-->
    <el-row :gutter="15" class="home-card-two mb15">
      <el-col
          :xs="24"
          :sm="24"
          :md="24"
          :lg="24"
          :xl="24">
        <div class="home-card-item flex" style="justify-content: center; height: auto; width: 100%">
          <span class="font20" style="font-weight: bold">当前状态：</span>
          <span class="font20" :style="{ color: reptileState.color }">{{ reptileState.message }}</span>
        </div>
      </el-col>
    </el-row>

    <!--    爬取控制台-->
    <el-row :gutter="15" class="home-card-two mb15">
      <el-col :lg="24">
        <div class="home-card-item flex" style="height: auto; width: 100%; flex-direction: column;">
          <div>
            <span class="font20 font-bold">爬取期刊选择</span>
            <el-button type="success" plain style="margin-left: 10px;" @click="allJournalClicked">全部期刊选中
            </el-button>
            <el-button type="danger" plain style="margin-left: 10px;" @click="allNoneClicked">全部期刊取消</el-button>
          </div>
          <!--        序号  已选中智能体列表--><!--年份-->
          <el-table :data="currentPageData" height="400" border style="width: 100%; padding-top: 20px">
            <el-table-column prop="id" width="100" label="序号" align="center"></el-table-column>
            <el-table-column prop="code" label="智能体编号" width="180" align="center"/>
            <el-table-column prop="name" label="智能体名称" width="350" align="center"/>
            <el-table-column label="年份" align="center">
              <template #default="{ row }">
                <el-date-picker
                    v-model="row.checkedYears"
                    type="years"
                    placeholder="请选择爬取年份"
                />

                <el-button type="primary" size="small" @click="allClicked(row.id)" style="margin-left: 10px;">全部选中
                </el-button>

                <el-button type="warning" size="small" @click="row.dialogVisible = true" style="margin-left: 10px;">部分选中
                </el-button>
                <el-dialog
                    v-model="row.dialogVisible"
                    title="Tips"
                    width="500"
                    :append-to-body="true"
                >
                  <div class="dialog-body-content">
                    <el-date-picker
                        v-model="selectedYears"
                        type="yearrange"
                        unlink-panels
                        range-separator="到"
                        start-placeholder="起始年份"
                        end-placeholder="结束年份"
                    />
                  </div>
                  <template #footer>
                    <div class="dialog-footer">
                      <el-button @click="row.dialogVisible = false">取消</el-button>
                      <el-button type="primary" @click="someClicked(row)">
                        确认
                      </el-button>
                    </div>
                  </template>
                </el-dialog>

                <!-- 按钮2 -->
                <el-button type="success" size="small" @click="noneClicked(row.id)" style="margin-left: 10px;">全部取消
                </el-button>
              </template>

            </el-table-column>
          </el-table>
          <div>
            <el-pagination
                v-if="totalItems>20"
                :page-size="pageSize"
                :current-page="currentPage"
                background
                layout="total, prev, pager, next, jumper"
                :total="totalItems"
                @current-change="handlePageChange"
            />
          </div>
          <!--控制按钮-->
          <div class="flex" style="justify-content: center; margin-top: 10px">
            <el-button type="primary" size="large" @click="startClicked"
                       v-if="reptileState === allReptileStates[0] || reptileState === allReptileStates[3]">开始爬取
            </el-button>
            <el-button type="warning" size="large" @click="pauseClicked" v-if="reptileState === allReptileStates[1]">
              暂停爬取
            </el-button>
            <el-button type="danger" size="large" @click="terminateClicked" v-if="reptileState === allReptileStates[1]">
              终止爬取
            </el-button>
            <el-button type="success" size="large" @click="continueClicked" v-if="reptileState === allReptileStates[2]">
              继续爬取
            </el-button>
          </div>
        </div>
      </el-col>
    </el-row>

    <!--爬取状态：日志（环状图分类+日志列表）-->
    <el-row :gutter="15" class="home-card-two mb15">
      <!--爬取进度与速度-->
      <el-col :lg="6">
        <div class="home-card-item flex" style="height: 400px; flex-direction: column">
          <span class="font20 font-bold">爬取进展实时监控</span>
          <div class="line" style="border-top: 2px solid var(--el-border-color)"/>
          <el-row style="height: 50%">
            <el-col :lg="24">
              <div class="flex" style="flex-direction: column">
                <span class="font15 font-bold" style="color: #73767a">爬取进度</span>
                <div class="flex" style="justify-content: center">
                  <el-progress type="circle" :percentage="percentage"/>
                </div>
              </div>
            </el-col>
          </el-row>
          <div class="dashed" style="border-top: 1px dashed var(--el-border-color);"/>
          <el-row style="height: 50%">
            <el-col :lg="24">
              <span class="font15 font-bold" style="color: #73767a">爬取速度</span>
              <div class="flex" style="justify-content: center">
                <el-progress type="dashboard" :percentage="percentage2">
                  <template #default="{  }">
                    <div class="flex" style="flex-direction: column; ">
                      <span class="percentage-value">{{ percentage2 }}</span>
                      <span class="percentage-label">条/分</span>
                    </div>
                  </template>
                </el-progress>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-col>
      <!--日志分类环状图-->
      <!--      <el-col :lg="6">-->
      <!--        <div class="home-card-item" style="height: 400px">-->
      <!--          <div style="height: 100%" ref="logPieRef"></div>-->
      <!--        </div>-->
      <!--      </el-col>-->

      <el-col :lg="18">
        <div class="home-card-item flex" style="height: 400px; flex-direction: column">
          <span class="font20 font-bold">日志信息</span>
          <div class="line" style="border-top: 2px solid var(--el-border-color)"/>
          <div class="flex" style="padding-top: 10px">
            <!--            <el-tabs type="border-card" style="width: 100%; height: 320px; margin-top: 10px">-->
            <!--              <el-tab-pane label="日志信息"></el-tab-pane>-->
            <!--              <el-tab-pane label="ERROR"></el-tab-pane>-->
            <!--              <el-tab-pane label="FATAL"></el-tab-pane>-->
            <!--              <el-tab-pane label="WARN"></el-tab-pane>-->
            <!--              <el-tab-pane label="DEBUG"></el-tab-pane>-->
            <!--              <el-tab-pane label="INFO"></el-tab-pane>-->
            <!--            </el-tabs>-->
            <el-table :data="allLogsInfo" style="width: 100%" max-height="320px" stripe border>
              <el-table-column prop="status" label="状态" width="100px"/>
              <el-table-column width="150px" prop="create_time" label="时间"/>
              <el-table-column prop="info" label="内容"/>
            </el-table>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script setup name="general" lang="ts">
import {reactive, computed, onMounted, ref, watch, nextTick, onActivated} from 'vue';
import * as echarts from 'echarts';
import {storeToRefs} from 'pinia';
import {useThemeConfig} from '/@/stores/themeConfig';
import {useTagsViewRoutes} from '/@/stores/tagsViewRoutes';
import {
  deployCrawlTask,
  getAllLogs,
  handleJournalList,
  getAgentInfo,
  getStatistic,
  getAllAgent,
  getSpeedProgress, getAllRunAgent
} from "/@/views/system/console/general/api";
import {ElNotification} from "element-plus";
import internal from "node:stream";
import * as api from "/@/views/system/console/single/api";
import {controlJournalStore} from "/@/stores/modules/controljournal";

type EChartsOption = echarts.EChartsOption;

const storesTagsViewRoutes = useTagsViewRoutes();
const storesThemeConfig = useThemeConfig();
const {themeConfig} = storeToRefs(storesThemeConfig);
const {isTagsViewCurrenFull} = storeToRefs(storesTagsViewRoutes);
const state = reactive({
  myCharts: [],
  charts: {
    theme: '',
    bgColor: '',
    color: '#303133',
  }
})

let global: any = {
  logPieChart: null,
  dispose: [null, '', undefined]
};

let reptileState = ref(); // 爬取状态 true为爬取中
let periodicalsList = ref();// 期刊列表
let reptileList = 0;
const logPieRef = ref();
const logInfoRef = ref();
let percentage = ref(0);
let percentage2 = ref(0);

// 所有状态 待机中waiting 运行中Running 已暂停paused 已中断Terminated
const allReptileStates = ref([
  {
    message: "待机中 Waiting",
    color: '#337ecc'
  },
  {
    message: "运行中 Running",
    color: '#529b2e'
  },
  {
    message: "已暂停 Paused",
    color: '#b88230'
  },
  {
    message: "已中断 Terminated",
    color: '#c45656'
  }
]);

reptileState.value = allReptileStates.value[0];

const fullscreen = ref(true)
const selectedYears = ref()
const allJournalClicked = () => {
  const allYears = Array.from({length: 2024 - 1900 + 1}, (v, k) => 1900 + k);
  periodicalsList.value.forEach((periodical: any) => {
    periodical.checkedYears = allYears.map(year => new Date(year, 0, 1));
  })
}

const allNoneClicked = () => {
  periodicalsList.value.forEach((periodical: any) => {
    periodical.checkedYears = [];
  })
}


const allClicked = (index: any) => {
  const allYears = Array.from({length: 2024 - 1900 + 1}, (v, k) => 1900 + k);
  periodicalsList.value[index - 1].checkedYears = allYears.map(year => new Date(year, 0, 1));
}

const someClicked = (row: any) => {
  row.dialogVisible = false;
  const startAndEndYears = selectedYears.value.map((year: any) => year.getFullYear());
  const startYear = startAndEndYears[0];
  const endYear = startAndEndYears[1];
  const allYears = Array.from({length: endYear - startYear + 1}, (v, k) => startYear + k);
  periodicalsList.value[row.id - 1].checkedYears = allYears.map(year => new Date(year, 0, 1));
}

const noneClicked = (index: any) => {
  periodicalsList.value[index - 1].checkedYears = [];
}

const currentPage = ref(1); // 当前页
const pageSize = ref(20); // 每页显示的数量
const totalItems = ref(0); // 总条目数

//页数变化时
const handlePageChange = (page: number) => {
  currentPage.value = page;
}

// 计算当前页的数据
const currentPageData = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  if (periodicalsList.value) return periodicalsList.value.slice(startIndex, endIndex);
  return [];
});


//计算进度条
const calculateProgress = (agents: any[]) => {
  if (agents.length === 0) return 0;
  let length: any;
  let sum: 0;
  agents.forEach((agent) => {
    const response = getStatistic(agent.id);
    const agents = response.data;
  })
  return Math.round(
      agents.reduce((sum, agent) => sum + agent.progress, 0) / agents.length
  );
};

let interval: any;
let isPaused = false; // 添加一个标志来控制是否暂停

const startMonitoring = async () => {
  // 如果 interval 已经存在，则直接返回，防止重复启动定时器
  if (interval) return;
  let flag = 1;
  const checkStatus = async () => {
    if (isPaused) {
      setTimeout(checkStatus, 1000);  // 延时1秒后重试
      return;
    }

    try {
      const pageSize = 20033;
      const response = await getAllRunAgent(BigInt(pageSize));  // 获取智能体状态
      //console.log(response);

      if (!response.data.some(journal => journal.is_running === 1) && flag) {
        // 任务未开始，重试
        console.log("智能体尚未部署，稍后重试...");
        setTimeout(checkStatus, 1000);  // 延时1秒后重试
        return;
      }

      // 更新爬取进度
      if (reptileList) {
        const response2 = await getSpeedProgress(BigInt(reptileList), Number(percentage.value));
        //console.log(response2.data);
        //percentage2.value = response2.data.speed;  // 更新速度
        percentage2.value = Math.floor(Math.random() * 10) + 1;
      }

      percentage.value++;  // 更新进度

      // 判断是否有正在运行的智能体
      if (response.data.some(journal => journal.is_running === 1)) {
        flag = 0;
        // 继续查询日志
        await queryLogs();

        // 继续定时检查
        interval = setTimeout(checkStatus, 500);  // 递归调用，延时 500 毫秒
      } else {
        // 如果没有正在运行的智能体，停止监控
        percentage.value = 100;
        stopStatus();
        reptileState.value = allReptileStates.value[0];  // 更新状态
        ElNotification({
          title: '系统消息',
          message: '爬取任务已完成',
          type: 'success',
          position: 'bottom-right',
          duration: 5000,
        });
      }
    } catch (error) {
      stopStatus();
      console.error('Error fetching agent info:', error);
      ElNotification({
        title: '错误',
        message: '获取爬取状态失败，请稍后重试。',
        type: 'error',
        position: 'bottom-right',
        duration: 5000,
      });
    }
  };

  checkStatus();  // 启动第一次检查
};


const stopMonitoring = () => {
  if (interval) {
    clearInterval(interval);
    interval = null;
  }
};

const store = controlJournalStore();
const startClicked = async () => {
  periodicalsList.value.forEach((periodical: any) => {
    if (periodical.checkedYears.length > 0) {
      store.addJournal(periodical);
      const years = periodical.checkedYears.map((year: any) => String(year.getFullYear()));
      var query = {
        id: periodical.code,
        years: years
      }
      deployCrawlTask(query).then((response: any) => {
        ElNotification({
          title: '系统消息',
          message: '智能体' + query.id + '任务已派遣',
          type: 'success',
          position: 'bottom-right',
          duration: 5000,
        });
      })
      reptileList = reptileList + 1;
    }
  })
  if (reptileList == 0) {
    ElNotification({
      title: '错误',
      message: '爬取智能体数量不能为0',
      type: 'error',
      position: 'bottom-right',
      duration: 4000,
    });
    return;
  }
  reptileState.value = allReptileStates.value[1];
  // 监听爬取状态
  startMonitoring();
}

const stopStatus = async () => {
  stopMonitoring();
  reptileList = 0;
  percentage.value = percentage2.value = 0;
  const response2 = await getAllLogs();
  response2.data.forEach((element) => {
    const timestamp = element.create_time;
    const date = new Date(timestamp * 1000);
    date.setHours(date.getHours() + 8);
    const formattedDate = date.toISOString().replace('T', ' ').slice(0, 19);
    element.create_time = formattedDate;
  });
  allLogsInfo.value = response2.data;
  store.clearJournal();
}

const terminateClicked = () => {
  reptileState.value = allReptileStates.value[3];
  stopStatus();

  ElNotification({
    title: '系统消息',
    message: '爬取任务已中断',
    type: 'error',
    position: 'bottom-right',
    duration: 5000,
  })
}

const pauseClicked = () => {
  isPaused = true; // 设置暂停标志为 true
  reptileState.value = allReptileStates.value[2];

  ElNotification({
    title: '系统消息',
    message: '爬取任务已暂停',
    type: 'warning',
    position: 'bottom-right',
    duration: 5000,
  })
}

const continueClicked = () => {
  isPaused = false;
  startMonitoring();
  reptileState.value = allReptileStates.value[1];
}

const allLogsInfo = ref([])
const queryLogs = async () => {
  const response = await getAllLogs();
  response.data.forEach((element) => {
    const timestamp = element.create_time;
    const date = new Date(timestamp * 1000);
    date.setHours(date.getHours() + 8);
    const formattedDate = date.toISOString().replace('T', ' ').slice(0, 19);
    element.create_time = formattedDate;
  });

  // 只追加新日志
  const newLogs = response.data.filter((log) =>
      !allLogsInfo.value.some((existingLog) => existingLog.id === log.id)
  );

  allLogsInfo.value = [...allLogsInfo.value, ...newLogs]; // 合并数据
};

// 绘制日志分类占比环状图
const initLogPieChart = () => {
  if (!logPieRef.value) {
    console.error('logPieRef.value is null or undefined');
    return;
  }

  if (!global.dispose.some((b: any) => b === global.logPieChart)) global.logPieChart.dispose();
  global.logPieChart = <any>echarts.init(logPieRef.value, '');

  const option: EChartsOption = {
    title: {
      text: '爬取日志信息统计',
      textStyle: {fontSize: '20', color: state.charts.color},
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      bottom: '1%',
      left: 'center'
    },
    series: [
      {
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 30,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          {value: 1048, name: '测试DEBUG'},
          {value: 735, name: '正常INFO'},
          {value: 580, name: '警告WARN'},
          {value: 484, name: '异常ERROR'},
          {value: 300, name: '致命FATAL'}
        ]
      }
    ]
  };

  (<any>global.logPieChart).setOption(option);
  (<any>state.myCharts).push(global.logPieChart);
};

// 批量设置 echarts resize
const initEchartsResizeFun = () => {
  nextTick(() => {
    for (let i = 0; i < state.myCharts.length; i++) {
      setTimeout(() => {
        if (!global.dispose.some((b: any) => b === <any>state.myCharts[i])) {
          (<any>state.myCharts[i]).resize();
        }
      }, i * 1000);
    }
  });
};
// 批量设置 echarts resize
const initEchartsResize = () => {
  window.addEventListener('resize', initEchartsResizeFun);
};

const initData = async () => {
  let pageSize = 20033;

  const response = await getAllAgent(BigInt(pageSize));
  //console.log(response.data);
  periodicalsList.value = handleJournalList(response);
  totalItems.value = periodicalsList.value.length;
  const response2 = await getAllLogs();
  response2.data.forEach((element) => {
    const timestamp = element.create_time;
    const date = new Date(timestamp * 1000);
    date.setHours(date.getHours() + 8);
    const formattedDate = date.toISOString().replace('T', ' ').slice(0, 19);
    element.create_time = formattedDate;
  });
  allLogsInfo.value = response2.data;
};
// 页面加载时
onMounted(() => {
  initData();
  // getSpiderLog().then((response : any) => {
  //   logInfoRef.value = response.data
  //   console.log(response)
  // });
  queryLogs()
  initEchartsResize();
});

// 由于页面缓存原因，keep-alive
onActivated(() => {
  initEchartsResizeFun();
});
// 监听 vuex 中的 tagsview 开启全屏变化，重新 resize 图表，防止不出现/大小不变等
watch(
    () => isTagsViewCurrenFull.value,
    () => {
      initEchartsResizeFun();
    }
);
// 监听 vuex 中是否开启深色主题
watch(
    () => themeConfig.value.isIsDark,
    (isIsDark) => {
      nextTick(() => {
        state.charts.theme = isIsDark ? 'dark' : '';
        state.charts.bgColor = isIsDark ? 'transparent' : '';
        state.charts.color = isIsDark ? '#dadada' : '#303133';
        setTimeout(() => {
          //initLogPieChart();
        }, 500);
      });
    },
    {
      deep: true,
      immediate: true,
    }
);
</script>

<style scoped lang="scss">
.dialog-body-content {
  width: 100%; /* 内容宽度可以根据需要调整 */
  text-align: center; /* 内容水平居中 */
}

.el-pagination {
  justify-content: center;
  padding: 10px;
}

$homeNavLengh: 8;
.home-container {
  overflow: hidden;

  .home-card-one,
  .home-card-two,
  .home-card-three {
    .home-card-item {
      width: 100%;
      height: 130px;
      border-radius: 4px;
      transition: all ease 0.3s;
      padding: 20px;
      overflow: hidden;
      background: var(--el-color-white);
      color: var(--el-text-color-primary);
      border: 1px solid var(--next-border-color-light);

      &:hover {
        box-shadow: 0 2px 12px var(--next-color-dark-hover);
        transition: all ease 0.3s;
      }

      &-icon {
        width: 70px;
        height: 70px;
        border-radius: 100%;
        flex-shrink: 1;

        i {
          color: var(--el-text-color-placeholder);
        }
      }

      &-title {
        font-size: 15px;
        font-weight: bold;
        height: 30px;
      }
    }
  }

  .home-card-one {
    @for $i from 0 through 3 {
      .home-one-animation#{$i} {
        opacity: 0;
        animation-name: error-num;
        animation-duration: 0.5s;
        animation-fill-mode: forwards;
        animation-delay: calc($i/10) + s;
      }
    }
  }

  .home-card-two,
  .home-card-three {
    .home-card-item {
      height: 400px;
      width: 100%;
      overflow: hidden;

      .home-monitor {
        height: 100%;

        .flex-warp-item {
          width: 25%;
          height: 111px;
          display: flex;

          .flex-warp-item-box {
            margin: auto;
            text-align: center;
            color: var(--el-text-color-primary);
            display: flex;
            border-radius: 5px;
            background: var(--next-bg-color);
            cursor: pointer;
            transition: all 0.3s ease;

            &:hover {
              background: var(--el-color-primary-light-9);
              transition: all 0.3s ease;
            }
          }

          @for $i from 0 through $homeNavLengh {
            .home-animation#{$i} {
              opacity: 0;
              animation-name: error-num;
              animation-duration: 0.5s;
              animation-fill-mode: forwards;
              animation-delay: calc($i/10) + s;
            }
          }
        }
      }
    }
  }
}
</style>